import type { IStudent, IStudentCreateRequest } from '@/types/student/student';
import type { ICourse, ICourseCreateRequest } from '@/types/course/course';
import type { IScheduleTemplate, IScheduleTemplateCreateRequest } from '@/types/schedule/scheduleTemplate';
import type { IScheduleInstance, IScheduleInstanceCreateRequest } from '@/types/schedule/scheduleInstance';
import { isValidDate, isValidTime } from '@/utils/date';

/**
 * 验证结果接口
 */
export interface IValidationResult {
  /** 是否验证通过 */
  isValid: boolean;
  /** 错误信息列表 */
  errors: string[];
  /** 警告信息列表 */
  warnings?: string[];
}

/**
 * 字段验证结果接口
 */
export interface IFieldValidationResult {
  /** 字段名 */
  field: string;
  /** 是否验证通过 */
  isValid: boolean;
  /** 错误信息 */
  message?: string;
}

/**
 * 数据验证工具类
 * @description 提供各种数据验证功能
 */
export class DataValidator {
  /**
   * 验证必填字段
   * @param value 字段值
   * @param fieldName 字段名称
   * @returns 验证结果
   */
  static validateRequired(value: unknown, fieldName: string): IFieldValidationResult {
    const isEmpty = value === null || value === undefined || 
                   (typeof value === 'string' && value.trim() === '') ||
                   (Array.isArray(value) && value.length === 0);

    return {
      field: fieldName,
      isValid: !isEmpty,
      message: isEmpty ? `${fieldName}不能为空` : undefined
    };
  }

  /**
   * 验证字符串长度
   * @param value 字符串值
   * @param fieldName 字段名称
   * @param minLength 最小长度
   * @param maxLength 最大长度
   * @returns 验证结果
   */
  static validateStringLength(
    value: string, 
    fieldName: string, 
    minLength?: number, 
    maxLength?: number
  ): IFieldValidationResult {
    if (typeof value !== 'string') {
      return {
        field: fieldName,
        isValid: false,
        message: `${fieldName}必须是字符串类型`
      };
    }

    const length = value.trim().length;

    if (minLength !== undefined && length < minLength) {
      return {
        field: fieldName,
        isValid: false,
        message: `${fieldName}长度不能少于${minLength}个字符`
      };
    }

    if (maxLength !== undefined && length > maxLength) {
      return {
        field: fieldName,
        isValid: false,
        message: `${fieldName}长度不能超过${maxLength}个字符`
      };
    }

    return {
      field: fieldName,
      isValid: true
    };
  }

  /**
   * 验证数字范围
   * @param value 数字值
   * @param fieldName 字段名称
   * @param min 最小值
   * @param max 最大值
   * @returns 验证结果
   */
  static validateNumberRange(
    value: number, 
    fieldName: string, 
    min?: number, 
    max?: number
  ): IFieldValidationResult {
    if (typeof value !== 'number' || isNaN(value)) {
      return {
        field: fieldName,
        isValid: false,
        message: `${fieldName}必须是有效的数字`
      };
    }

    if (min !== undefined && value < min) {
      return {
        field: fieldName,
        isValid: false,
        message: `${fieldName}不能小于${min}`
      };
    }

    if (max !== undefined && value > max) {
      return {
        field: fieldName,
        isValid: false,
        message: `${fieldName}不能大于${max}`
      };
    }

    return {
      field: fieldName,
      isValid: true
    };
  }

  /**
   * 验证邮箱格式
   * @param email 邮箱地址
   * @param fieldName 字段名称
   * @returns 验证结果
   */
  static validateEmail(email: string, fieldName: string = '邮箱'): IFieldValidationResult {
    if (!email || typeof email !== 'string') {
      return {
        field: fieldName,
        isValid: true // 邮箱通常是可选字段
      };
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const isValid = emailRegex.test(email.trim());

    return {
      field: fieldName,
      isValid,
      message: isValid ? undefined : `${fieldName}格式不正确`
    };
  }

  /**
   * 验证手机号格式
   * @param phone 手机号
   * @param fieldName 字段名称
   * @returns 验证结果
   */
  static validatePhone(phone: string, fieldName: string = '手机号'): IFieldValidationResult {
    if (!phone || typeof phone !== 'string') {
      return {
        field: fieldName,
        isValid: true // 手机号通常是可选字段
      };
    }

    // 中国大陆手机号格式验证
    const phoneRegex = /^1[3-9]\d{9}$/;
    const isValid = phoneRegex.test(phone.trim());

    return {
      field: fieldName,
      isValid,
      message: isValid ? undefined : `${fieldName}格式不正确`
    };
  }

  /**
   * 验证日期格式
   * @param date 日期字符串
   * @param fieldName 字段名称
   * @returns 验证结果
   */
  static validateDate(date: string, fieldName: string): IFieldValidationResult {
    if (!date || typeof date !== 'string') {
      return {
        field: fieldName,
        isValid: false,
        message: `${fieldName}不能为空`
      };
    }

    const isValid = isValidDate(date);
    return {
      field: fieldName,
      isValid,
      message: isValid ? undefined : `${fieldName}格式不正确，请使用YYYY-MM-DD格式`
    };
  }

  /**
   * 验证时间格式
   * @param time 时间字符串
   * @param fieldName 字段名称
   * @returns 验证结果
   */
  static validateTime(time: string, fieldName: string): IFieldValidationResult {
    if (!time || typeof time !== 'string') {
      return {
        field: fieldName,
        isValid: false,
        message: `${fieldName}不能为空`
      };
    }

    const isValid = isValidTime(time);
    return {
      field: fieldName,
      isValid,
      message: isValid ? undefined : `${fieldName}格式不正确，请使用HH:mm格式`
    };
  }

  /**
   * 验证颜色格式
   * @param color 颜色值
   * @param fieldName 字段名称
   * @returns 验证结果
   */
  static validateColor(color: string, fieldName: string = '颜色'): IFieldValidationResult {
    if (!color || typeof color !== 'string') {
      return {
        field: fieldName,
        isValid: false,
        message: `${fieldName}不能为空`
      };
    }

    // 支持十六进制颜色格式 #RRGGBB 或 #RGB
    const hexColorRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
    const isValid = hexColorRegex.test(color.trim());

    return {
      field: fieldName,
      isValid,
      message: isValid ? undefined : `${fieldName}格式不正确，请使用十六进制格式（如#FF0000）`
    };
  }

  /**
   * 验证数组不为空
   * @param array 数组值
   * @param fieldName 字段名称
   * @returns 验证结果
   */
  static validateArrayNotEmpty(array: unknown[], fieldName: string): IFieldValidationResult {
    const isValid = Array.isArray(array) && array.length > 0;
    return {
      field: fieldName,
      isValid,
      message: isValid ? undefined : `${fieldName}至少需要选择一项`
    };
  }

  /**
   * 验证学生信息
   * @param studentData 学生数据
   * @returns 验证结果
   */
  static validateStudentData(studentData: IStudentCreateRequest): IValidationResult {
    const errors: string[] = [];
    const warnings: string[] = [];

    // 验证必填字段
    const nameValidation = this.validateRequired(studentData.name, '学生姓名');
    if (!nameValidation.isValid) {
      errors.push(nameValidation.message!);
    } else {
      const nameLengthValidation = this.validateStringLength(studentData.name, '学生姓名', 1, 50);
      if (!nameLengthValidation.isValid) {
        errors.push(nameLengthValidation.message!);
      }
    }

    const studentIdValidation = this.validateRequired(studentData.studentId, '学号');
    if (!studentIdValidation.isValid) {
      errors.push(studentIdValidation.message!);
    } else {
      const studentIdLengthValidation = this.validateStringLength(studentData.studentId, '学号', 1, 20);
      if (!studentIdLengthValidation.isValid) {
        errors.push(studentIdLengthValidation.message!);
      }
    }

    // 验证可选字段
    if (studentData.phone) {
      const phoneValidation = this.validatePhone(studentData.phone, '联系电话');
      if (!phoneValidation.isValid) {
        errors.push(phoneValidation.message!);
      }
    }

    if (studentData.parentPhone) {
      const parentPhoneValidation = this.validatePhone(studentData.parentPhone, '家长联系电话');
      if (!parentPhoneValidation.isValid) {
        errors.push(parentPhoneValidation.message!);
      }
    }

    if (studentData.email) {
      const emailValidation = this.validateEmail(studentData.email, '邮箱地址');
      if (!emailValidation.isValid) {
        errors.push(emailValidation.message!);
      }
    }

    if (studentData.age !== undefined) {
      const ageValidation = this.validateNumberRange(studentData.age, '年龄', 3, 100);
      if (!ageValidation.isValid) {
        errors.push(ageValidation.message!);
      }
    }

    if (studentData.birthDate) {
      const birthDateValidation = this.validateDate(studentData.birthDate, '出生日期');
      if (!birthDateValidation.isValid) {
        errors.push(birthDateValidation.message!);
      }
    }

    if (studentData.enrollmentDate) {
      const enrollmentDateValidation = this.validateDate(studentData.enrollmentDate, '入学日期');
      if (!enrollmentDateValidation.isValid) {
        errors.push(enrollmentDateValidation.message!);
      }
    }

    // 添加警告信息
    if (!studentData.phone && !studentData.parentPhone) {
      warnings.push('建议至少填写一个联系电话');
    }

    return {
      isValid: errors.length === 0,
      errors,
      warnings
    };
  }

  /**
   * 验证课程信息
   * @param courseData 课程数据
   * @returns 验证结果
   */
  static validateCourseData(courseData: ICourseCreateRequest): IValidationResult {
    const errors: string[] = [];
    const warnings: string[] = [];

    // 验证必填字段
    const nameValidation = this.validateRequired(courseData.name, '课程名称');
    if (!nameValidation.isValid) {
      errors.push(nameValidation.message!);
    } else {
      const nameLengthValidation = this.validateStringLength(courseData.name, '课程名称', 1, 100);
      if (!nameLengthValidation.isValid) {
        errors.push(nameLengthValidation.message!);
      }
    }

    const courseCodeValidation = this.validateRequired(courseData.courseCode, '课程代码');
    if (!courseCodeValidation.isValid) {
      errors.push(courseCodeValidation.message!);
    } else {
      const courseCodeLengthValidation = this.validateStringLength(courseData.courseCode, '课程代码', 1, 20);
      if (!courseCodeLengthValidation.isValid) {
        errors.push(courseCodeLengthValidation.message!);
      }
    }

    const teacherValidation = this.validateRequired(courseData.teacher, '授课教师');
    if (!teacherValidation.isValid) {
      errors.push(teacherValidation.message!);
    } else {
      const teacherLengthValidation = this.validateStringLength(courseData.teacher, '授课教师', 1, 50);
      if (!teacherLengthValidation.isValid) {
        errors.push(teacherLengthValidation.message!);
      }
    }

    const colorValidation = this.validateColor(courseData.color, '课程颜色');
    if (!colorValidation.isValid) {
      errors.push(colorValidation.message!);
    }

    const categoryIdsValidation = this.validateArrayNotEmpty(courseData.categoryIds, '课程分类');
    if (!categoryIdsValidation.isValid) {
      errors.push(categoryIdsValidation.message!);
    }

    // 验证可选字段
    if (courseData.duration !== undefined) {
      const durationValidation = this.validateNumberRange(courseData.duration, '课程时长', 15, 480);
      if (!durationValidation.isValid) {
        errors.push(durationValidation.message!);
      }
    }

    if (courseData.fee !== undefined) {
      const feeValidation = this.validateNumberRange(courseData.fee, '课程费用', 0, 10000);
      if (!feeValidation.isValid) {
        errors.push(feeValidation.message!);
      }
    }

    if (courseData.capacity !== undefined) {
      const capacityValidation = this.validateNumberRange(courseData.capacity, '课程容量', 1, 100);
      if (!capacityValidation.isValid) {
        errors.push(capacityValidation.message!);
      }
    }

    // 添加警告信息
    if (!courseData.description) {
      warnings.push('建议添加课程描述');
    }

    if (!courseData.duration) {
      warnings.push('建议设置课程时长');
    }

    return {
      isValid: errors.length === 0,
      errors,
      warnings
    };
  }

  /**
   * 验证课程安排模板信息
   * @param templateData 课程安排模板数据
   * @returns 验证结果
   */
  static validateScheduleTemplateData(templateData: IScheduleTemplateCreateRequest): IValidationResult {
    const errors: string[] = [];
    const warnings: string[] = [];

    // 验证必填字段
    const studentIdValidation = this.validateRequired(templateData.studentId, '学生');
    if (!studentIdValidation.isValid) {
      errors.push(studentIdValidation.message!);
    }

    const courseIdValidation = this.validateRequired(templateData.courseId, '课程');
    if (!courseIdValidation.isValid) {
      errors.push(courseIdValidation.message!);
    }

    const startDateValidation = this.validateDate(templateData.startDate, '开始日期');
    if (!startDateValidation.isValid) {
      errors.push(startDateValidation.message!);
    }

    const startTimeValidation = this.validateTime(templateData.startTime, '开始时间');
    if (!startTimeValidation.isValid) {
      errors.push(startTimeValidation.message!);
    }

    const endTimeValidation = this.validateTime(templateData.endTime, '结束时间');
    if (!endTimeValidation.isValid) {
      errors.push(endTimeValidation.message!);
    }

    // 验证时间逻辑
    if (startTimeValidation.isValid && endTimeValidation.isValid) {
      const startMinutes = this.timeToMinutes(templateData.startTime);
      const endMinutes = this.timeToMinutes(templateData.endTime);
      
      if (endMinutes <= startMinutes) {
        errors.push('结束时间必须晚于开始时间');
      }
    }

    const totalCountValidation = this.validateNumberRange(templateData.totalCount, '总次数', 1, 1000);
    if (!totalCountValidation.isValid) {
      errors.push(totalCountValidation.message!);
    }

    // 验证星期几
    if (templateData.dayOfWeek < 1 || templateData.dayOfWeek > 7) {
      errors.push('星期几必须在1-7之间');
    }

    // 验证可选字段
    if (templateData.feePerSession !== undefined) {
      const feeValidation = this.validateNumberRange(templateData.feePerSession, '单次费用', 0, 1000);
      if (!feeValidation.isValid) {
        errors.push(feeValidation.message!);
      }
    }

    if (templateData.maxMakeupCount !== undefined) {
      const makeupCountValidation = this.validateNumberRange(templateData.maxMakeupCount, '最大补课次数', 0, 50);
      if (!makeupCountValidation.isValid) {
        errors.push(makeupCountValidation.message!);
      }
    }

    return {
      isValid: errors.length === 0,
      errors,
      warnings
    };
  }

  /**
   * 验证课程实例信息
   * @param instanceData 课程实例数据
   * @returns 验证结果
   */
  static validateScheduleInstanceData(instanceData: IScheduleInstanceCreateRequest): IValidationResult {
    const errors: string[] = [];
    const warnings: string[] = [];

    // 验证必填字段
    const templateIdValidation = this.validateRequired(instanceData.templateId, '课程模板');
    if (!templateIdValidation.isValid) {
      errors.push(templateIdValidation.message!);
    }

    const studentIdValidation = this.validateRequired(instanceData.studentId, '学生');
    if (!studentIdValidation.isValid) {
      errors.push(studentIdValidation.message!);
    }

    const courseIdValidation = this.validateRequired(instanceData.courseId, '课程');
    if (!courseIdValidation.isValid) {
      errors.push(courseIdValidation.message!);
    }

    const dateValidation = this.validateDate(instanceData.date, '日期');
    if (!dateValidation.isValid) {
      errors.push(dateValidation.message!);
    }

    const startTimeValidation = this.validateTime(instanceData.startTime, '开始时间');
    if (!startTimeValidation.isValid) {
      errors.push(startTimeValidation.message!);
    }

    const endTimeValidation = this.validateTime(instanceData.endTime, '结束时间');
    if (!endTimeValidation.isValid) {
      errors.push(endTimeValidation.message!);
    }

    // 验证时间逻辑
    if (startTimeValidation.isValid && endTimeValidation.isValid) {
      const startMinutes = this.timeToMinutes(instanceData.startTime);
      const endMinutes = this.timeToMinutes(instanceData.endTime);
      
      if (endMinutes <= startMinutes) {
        errors.push('结束时间必须晚于开始时间');
      }
    }

    const sequenceNumberValidation = this.validateNumberRange(instanceData.sequenceNumber, '课程序号', 1, 1000);
    if (!sequenceNumberValidation.isValid) {
      errors.push(sequenceNumberValidation.message!);
    }

    // 验证可选字段
    if (instanceData.fee !== undefined) {
      const feeValidation = this.validateNumberRange(instanceData.fee, '课程费用', 0, 1000);
      if (!feeValidation.isValid) {
        errors.push(feeValidation.message!);
      }
    }

    return {
      isValid: errors.length === 0,
      errors,
      warnings
    };
  }

  /**
   * 将时间字符串转换为分钟数（辅助方法）
   * @param timeString 时间字符串
   * @returns 分钟数
   */
  private static timeToMinutes(timeString: string): number {
    const [hours, minutes] = timeString.split(':').map(Number);
    return hours * 60 + minutes;
  }
}

/**
 * 导出便捷验证函数
 */

/**
 * 验证学生数据
 */
export const validateStudentData = (studentData: IStudentCreateRequest): { isValid: boolean; message?: string } => {
  const result = DataValidator.validateStudentData(studentData);
  return {
    isValid: result.isValid,
    message: result.errors.length > 0 ? result.errors[0] : undefined
  };
};

/**
 * 验证课程数据
 */
export const validateCourseData = (courseData: ICourseCreateRequest): { isValid: boolean; message?: string } => {
  const result = DataValidator.validateCourseData(courseData);
  return {
    isValid: result.isValid,
    message: result.errors.length > 0 ? result.errors[0] : undefined
  };
};

/**
 * 验证课程安排模板数据
 */
export const validateScheduleTemplateData = (templateData: IScheduleTemplateCreateRequest): { isValid: boolean; message?: string } => {
  const result = DataValidator.validateScheduleTemplateData(templateData);
  return {
    isValid: result.isValid,
    message: result.errors.length > 0 ? result.errors[0] : undefined
  };
};

/**
 * 验证课程实例数据
 */
export const validateScheduleInstanceData = (instanceData: IScheduleInstanceCreateRequest) => 
  DataValidator.validateScheduleInstanceData(instanceData);

/**
 * 验证必填字段
 */
export const validateRequired = (value: unknown, fieldName: string) => 
  DataValidator.validateRequired(value, fieldName);

/**
 * 验证邮箱格式
 */
export const validateEmail = (email: string, fieldName?: string) => 
  DataValidator.validateEmail(email, fieldName);

/**
 * 验证手机号格式
 */
export const validatePhone = (phone: string, fieldName?: string) => 
  DataValidator.validatePhone(phone, fieldName);